package logic

import (
	"encoding/csv"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"gvb-server/global"
	"gvb-server/models"
	"gvb-server/utils"
	"log"
	"mime/multipart"
	"os"
)

func (pl Pub) Roles() ([]models.Roles, error) {
	var role []models.Roles
	var rb utils.PubStatus

	w := map[string]any{
		"status": 1,
	}

	err = global.DB.Where(w).Find(&role).Error

	rb.Status = 200
	return role, err
}

func (pl Pub) Departments() ([]models.Departments, error) {
	var dep []models.Departments
	var rb utils.PubStatus

	w := map[string]any{
		"status": 1,
	}

	err = global.DB.Where(w).Find(&dep).Error

	rb.Status = 200
	return dep, err
}

// UploadExcel 上传excel ,读取xlsx，xls和 csv的方式不一样
func (pl Pub) UploadExcel(file *multipart.FileHeader, c *gin.Context, fileBash string, filePath string) (Pub utils.PubStatus) {
	// 打开现有的 Excel 文件
	filePathName := fileBash + "/" + file.Filename
	err = c.SaveUploadedFile(file, filePathName)
	if err != nil {
		Pub.Status = utils.ERROR
		Pub.Msg = "文件保存失败！"
		return
	}

	fmt.Print("file.Filenamefile.Filenamefile.Filename\n")
	fmt.Print(filePathName)

	// 打开 CSV 文件
	csvFile, err := os.Open(filePathName)
	if err != nil {
		log.Fatalf("failed to open csv file: %v", err)
	}
	defer csvFile.Close()

	// 读取 CSV 文件
	reader := csv.NewReader(csvFile)
	records, err := reader.ReadAll()
	if err != nil {
		log.Fatalf("failed to read csv file: %v", err)
	}

	// 打印所有记录
	for k, record := range records {
		fmt.Printf("第%d", k) // record 是 []string，包含了单行的所有字段值
		fmt.Println(record)  // record 是 []string，包含了单行的所有字段值
	}
	return

	// 读取上传的Excel文件
	xlsx, err := excelize.OpenFile(filePathName)
	//xlsx, err := excelize.OpenFile("uploads/file/abc2.xlsx")

	if err != nil {
		fmt.Print("------------- data 22 -----------------------")
		Pub.Status = utils.ERROR
		Pub.Msg = err.Error()
		return
	}

	// 读取Excel中的数据
	rows, err := xlsx.GetRows("Sheet1")
	if err != nil {
		Pub.Status = utils.SUCCESS
		return
	}

	// 处理Excel数据
	var data []map[string]string
	for _, row := range rows {
		rowData := make(map[string]string)
		for i, cell := range row {
			// 假设第一行是标题
			title := rows[0][i]
			rowData[title] = cell
		}
		data = append(data, rowData)
	}
	fmt.Print("------------- data -----------------------")
	fmt.Print(data)

	//返回
	Pub.Status = utils.SUCCESS
	return
}
